package com.example.mytestdemo.linearlayoutmanager.dragon

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.example.mytestdemo.utils.ScreenUtils
import kotlin.math.tan


/**
 * @author tgw
 * @date 2022/8/26
 * @describe
 *
 * 参考：https://blog.csdn.net/u011692041/article/details/76093920
 *
 * 实验 自定义view的测量过程
 *
 *
 * reset() 重置画
setColor(int color) 给画笔设置颜色值
setARGB(int a, int r, int g, int b) 同样是设置颜色，但是利用ARGB分开设置
setAlpha(int a) 设置画笔透明度
setStyle(Paint.Style style) 设置画笔样式
setStrokeWidth(float width) 设置画笔宽度
setAntiAlias(boolean aa) 设置画笔是否抗锯齿

上面这些函数我们都讲过，下面来看看一些新的函数
setStrokeCap(Paint.Cap cap) 设置线冒样式，取值有Cap.ROUND(圆形线冒)、Cap.SQUARE(方形线冒)、Paint.Cap.BUTT(无线冒)
setStrokeJoin(Paint.Join join) 设置线段连接处样式，取值有：Join.MITER（结合处为锐角）、Join.Round(结合处为圆弧)、Join.BEVEL(结合处为直线)
setStrokeMiter(float miter) 设置笔画的倾斜度，90度拿画笔与30拿画笔，画出来的线条样式肯定是不一样的吧。（事实证明，根本看不出来什么区别好吗……囧……）
setPathEffect(PathEffect effect) 设置路径样式;取值类型是所有派生自PathEffect的子类：ComposePathEffect, CornerPathEffect, DashPathEffect, DiscretePathEffect, PathDashPathEffect, SumPathEffect
 */
class DrawPathViewTest @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
)  : View(context,attrs,defStyleAttr) {

    companion object {
        private const val TAG = "DrawPathViewTest"
        //每隔10的长度计算一个点
        private const val PRECISION = 10

    }

    private var pathAllPointS= Keyframes(Path())

    private var pathPaint:Paint = Paint().apply {
        color = Color.parseColor("#000000")
        strokeWidth = 5f
        style = Paint.Style.STROKE
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        ScreenUtils.measureMode("$TAG widthMeasureSpec:",widthMeasureSpec)
        ScreenUtils.measureMode("$TAG heightMeasureSpec:",heightMeasureSpec)
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

    }


    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        canvas.drawPath( getPath(), pathPaint)
//        initPath(path)
    }

     fun getPath():Path {
       val path = Path()
        path.moveTo(250f, 50f)
        path.rLineTo(600f, 300f)
        path.rLineTo(-600f, 300f)
        path.rLineTo(600f, 300f)
        path.rLineTo(-600f, 300f)
        return path
    }


    private fun initPath(path: Path) {
        val pathMeasure = PathMeasure(path, false)
        val pathLength = pathMeasure.length
        val numPoints = ((pathLength / PRECISION)  + 1).toInt()
        pathAllPointS = Keyframes(path).apply {
            mX = FloatArray(numPoints)
            mY = FloatArray(numPoints)
            mAngle = FloatArray(numPoints)
        }
        //临时存放坐标点
        val position = FloatArray(2)
        //临时存放正切值
        val tangent = FloatArray(2)
        //当前距离
        var distance: Float
        for (i in 0 until numPoints) {
            //更新当前距离
            distance = i * pathLength / (numPoints - 1)
            //根据当前距离获取对应的坐标点和正切值
            pathMeasure.getPosTan(distance, position, tangent)
            pathAllPointS.mX?.set(i, position[0])
            pathAllPointS.mY?.set(i, position[1])
            //利用反正切函数得到角度 // https://www.cnblogs.com/yimeixiaobai1314/p/15698676.html
            // http://www.qiutianaimeili.com/html/page/2021/02/20314txw5nhe1uq.html
            //https://www.jianshu.com/p/04f3660b1f3a
            // 2Π = 360°，rad = deg x π / 180 （rad 是弧度， deg 是角度）
            // Math.tan(45*Math.PI/180)=0.99999999 tan45° = 1，
            // Math.atan(1)=45*Math.PI/180，
            //9.462322 170.53767
            pathAllPointS.mAngle?.set(i, fixAngle(
                (Math.atan2(
                    tangent[1].toDouble(),
                    tangent[0].toDouble()
                ) * 180f / Math.PI).toFloat()
            )
            )
        }

        //
        Log.d(TAG, "initPath 建立角度: ")
        for (i in 0 until numPoints) {
            Log.d(TAG, "initPath 建立角度 mx: ${pathAllPointS.mX?.get(i)}---my: ${pathAllPointS.mY?.get(i)}----mAnglex: ${pathAllPointS.mAngle?.get(i)}")
        }
    }

    /**
     * 调整角度，使其在0 ~ 360之间
     *
     * @param rotation 当前角度
     * @return 调整后的角度
     */
    private fun fixAngle(rotation: Float): Float {
        var rotation = rotation
        val angle = 360f
        if (rotation < 0) {
            rotation += angle
        }
        if (rotation > angle) {
            rotation %= angle
        }
        return rotation
    }


}